package com.hongyi.common.web.config;


import com.hongyi.common.framework.utils.string.StringUtils;
import com.hongyi.common.web.filter.RepeatableFilter;
import com.hongyi.common.web.filter.XssFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * Filter过滤器配置
 *
 * @author DingHao
 */
@Configuration
public class FilterConfig
{
    private static final Logger log = LoggerFactory.getLogger(FilterConfig.class);

    @Value("${xss.enabled}")
    private String enabled;

    @Value("${xss.excludes}")
    private String excludes;

    @Value("${xss.urlPatterns}")
    private String urlPatterns;

    /**
     * xss过滤器设置
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<Filter> xssFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", excludes);
        initParameters.put("enabled", enabled);
        registration.setInitParameters(initParameters);
        log.info("xss filter register bean success");
        return registration;
    }

    /**
     * 注册可重复读取请求体的过滤器
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })//编译器忽略与泛型相关的警告
    @Bean
    public FilterRegistrationBean someFilterRegistration()
    {
        //用于注册过滤器
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //设置过滤器实例为 RepeatableFilter
        registration.setFilter(new RepeatableFilter());
        //添加需要应用可重复读取请求体过滤器的 URL 模式，这里设置为 /*，表示所有 URL
        registration.addUrlPatterns("/*");
        //设置过滤器的名称为 repeatableFilter
        registration.setName("repeatableFilter");
        //设置过滤器的优先级为最低（LOWEST_PRECEDENCE），确保它在其他过滤器之后执行
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

}
